<?php
namespace hid\storages\memory;

use hid\base\IdBuilder;
use hid\base\IdStorage;
use Exception;
use hid\base\LocalStorage;

/**
 * php内存id存储器
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 */
class MemoryStorage extends LocalStorage
{

    protected $keys = [];

    public function lock(string $name,int $tll = 0):bool
    {
        $this->keys[$name] = 1;

        return true;
    }

    public function exists(string $name):bool
    {
        return isset($this->keys[$name]);
    }

    public function unlock(string $name):bool
    {
        unset($this->keys[$name]);

        return true;
    }

    public function setValue(string $name,$value):bool
    {
        $this->keys[$name] = $value;

        return true;
    }

    public function getValue(string $name)
    {
        return isset($this->keys[$name]) ? $this->keys[$name] : null;
    }

    public function incrBy(IdBuilder $idBuilder,int $step = 1):?int
    {
        $key = $idBuilder->getStoreKey();

        if (!isset($this->keys[$key])) {
            $this->keys[$key] = $idBuilder->getInitValueForStorage();
        }

        $this->keys[$key] = $this->keys[$key] + $step;

        return $this->keys[$key];
    }

}
